package com.landian.demo.distributedlock.springboot.service;

import com.landian.demo.distributedlock.springboot.enums.ResultEnum;
import com.landian.demo.distributedlock.springboot.exception.MyException;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

@Slf4j
public class UserThread extends Thread {

    private OrderService orderService;

    private String productId;

    private boolean showError;

    public UserThread(String userName, OrderService orderService, String productId, boolean showError) {
        super(userName);
        this.orderService = orderService;
        this.productId = productId;
        this.showError = showError;
    }

    @Override
    public void run() {
//        boolean over = false;
//        while (!over){
//            try {
//                orderService.secondKill(productId);
//            } catch (MyException e) {
//                Integer code = e.getCode();
//                if(showError){
//                    log.error(e.getMessage());
//                }
//                if(ResultEnum.OUT_STOCK.getCode().equals(code)){
//                    over = true;
//                }
//            }
//        }
        try {
            Random random = new Random();
            long sleepTime = random.nextInt(100);
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
        orderService.secondKill(productId);
    }
}
